<?php declare(strict_types=1);

/**
 * @author      guosir
 * @copyright   2023-2025 owner
 **/

namespace Srv\Apps\Apis\Order\Ctl;

use Srv\Apps\Proto\VO\Order\PayAppleKeyListVO;
use Srv\Apps\Proto\VO\Order\PayAppleKeyVO;
use Srv\Conf\ConfModel\AppleAuthConf;
use Srv\Conf\ConfModel\ConfExt;
use Srv\Libs\Common\CommArray;
use Srv\Libs\Common\CommJson;
use Srv\Libs\Frame\ControllerAbstract;
use Srv\Libs\Plugins\Apple\AppleStoreConnect;
use Srv\Libs\Storage\DataMysql;
use Srv\Libs\Storage\DataRedis;

final class PayAppleCtl extends ControllerAbstract
{
    private ?DataMysql $DbAuto              = null;                 // DB-Write
    private const APPLE_AUTH_GROUP_NAME     = 'connect';            // 配置分组名
    private ?AppleAuthConf $AppleAuthConf   = null;                 // PayAppleConf
    private ?DataRedis $CcAuto              = null;                 // Cache
    private int $CacheExpire                = 600;                  // Cache时长[秒]
    private string $CacheKey                = 'PAY_APPLE_KEY_LIST'; // Cache存储Key

    /**
     * @return static
     * tag
     */
    final public static function tag():self
    {
        $thisObject                         = self::tagGet();
        if($thisObject instanceof self){
            $thisObject->DbAuto             = self::getDbAuto();
            $thisObject->CcAuto             = self::getCacheAuto();
            $thisObject->AppleAuthConf      = ConfExt::getAppleAuthConfGroup()->getByGroupName(self::APPLE_AUTH_GROUP_NAME);
        }
        return $thisObject;
    }

    /**
     * @return PayAppleKeyListVO|null
     */
    public function getPayAppleKeyList():?PayAppleKeyListVO{

        $PayAppleKeyListVO      = new PayAppleKeyListVO();
        $list                   = $this->CcAuto->getAry($this->CacheKey);
        if(count($list) < 1 || !isset($list[0]['attributes']) || !is_array($list[0]['attributes']) || count($list[0]['attributes']) < 1){
            $list               = (new AppleStoreConnect($this->AppleAuthConf))->getInAppPurchasesV2List($this->AppleAuthConf->getAppId());
            if(count($list) > 0){
                $this->CcAuto->set($this->CacheKey, CommJson::encodeArray($list), $this->CacheExpire);
            }
        }
        if(CommArray::isForeach($list)){
            $PayAppleKeyVOList  = [];
            foreach ($list as $item){
                if(!isset($item['attributes']) || !is_array($item['attributes']) || count($item['attributes']) < 1) continue;
                $name                   = $item['attributes']['name'];
                $productId              = $item['attributes']['productId'];
                $state                  = $item['attributes']['state'];
                $label                  = $this->str_pad_user($name, 32, ' ').' | '.$this->str_pad_user($productId, 32, ' ').' | '.$state;
                $PayAppleKeyVO          = new PayAppleKeyVO();
                $PayAppleKeyVO->setName($name);
                $PayAppleKeyVO->setProductId($productId);
                $PayAppleKeyVO->setState($state);
                $PayAppleKeyVO->setLabel($label);
                $PayAppleKeyVOList[]    = $PayAppleKeyVO;
            }
            $PayAppleKeyListVO->setList($PayAppleKeyVOList);
        }
        return $PayAppleKeyListVO;
    }

    /**
     * @param string $str
     * @param int $length
     * @param string $padString
     * @return string
     * str_pad_user
     */
    private function str_pad_user(string $str, int $length=32, string $padString=''):string
    {
        $displayCount    = (strlen($str) - mb_strlen($str))/2;
        return str_pad($str, $length + $displayCount, $padString);
    }
}